package com.zoho.daliansheng.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zoho.daliansheng.common.U8SystemRecord;
import com.zoho.daliansheng.common.ZohoRecord;
import com.zoho.daliansheng.config.CRMPathConfig;
import com.zoho.daliansheng.config.CRMSqlQuery;
import com.zoho.daliansheng.config.DatasourceEnum;
import com.zoho.daliansheng.config.U8SystemPathConfig;
import com.zoho.daliansheng.dlcr.ApiReturnInfo;
import com.zoho.daliansheng.dlcr.DlcrU8WebService;
import com.zoho.daliansheng.dlcr.DlcrU8WebServiceSoap;
import com.zoho.daliansheng.utils.CrmApiUtil;
import com.zoho.daliansheng.utils.ResultUtil;
import com.zoho.daliansheng.utils.U8SystemApiUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Service
public class AccountServiceImpl implements AccountService {

    ZohoRecord zohoRecord;

    U8SystemRecord u8SystemRecord;

    U8SystemPathConfig u8SystemPathConfig;

    CRMPathConfig crmPathConfig;

    CRMSqlQuery crmSqlQuery;

    public AccountServiceImpl(ZohoRecord zohoRecord, U8SystemRecord u8SystemRecord, U8SystemPathConfig u8SystemPathConfig, CRMPathConfig crmPathConfig, CRMSqlQuery crmSqlQuery) {
        this.zohoRecord = zohoRecord;
        this.u8SystemRecord = u8SystemRecord;
        this.u8SystemPathConfig = u8SystemPathConfig;
        this.crmPathConfig = crmPathConfig;
        this.crmSqlQuery = crmSqlQuery;
    }

    @Override
    public ResultUtil<Object> pushAccountToERP(JSONObject json) {
        log.info("pushAccountToERP,parameter={}", json.toJSONString());

        String accountId = json.getString("accountId");
        if (StringUtils.isBlank(accountId)) {
            return ResultUtil.error("accountId为空");
        }

        // 1 获取CRM数据
        JSONObject accountData = CrmApiUtil.getDataById(zohoRecord.getAccessToken(), crmPathConfig.getAccountModuleName(), accountId);
        if (Objects.isNull(accountData)) {
            return ResultUtil.error("accountId数据为空");
        }

        String approvalState = accountData.getString("approvalstate"); // 审批状态
        if (!"批准".equals(approvalState)) {
            String errMsg = "单据未经审批，不允许推送。";
            JSONObject updateData = new JSONObject();
            updateData.put("id", accountId);
            updateData.put("push_status", "失败");
            updateData.put("fail_reason", errMsg);
            List<JSONObject> list = new ArrayList<>();
            list.add(updateData);
            CrmApiUtil.batchUpdateDataByList(zohoRecord.getAccessToken(), list, crmPathConfig.getAccountModuleName());


            return ResultUtil.error("单据未经审批，不允许推送。");
        }

        String khCompany = accountData.getString("KHCompany");
        String webServiceUrl = U8SystemApiUtil.getWebUrlByCompanyName(khCompany);
        if (StringUtils.isBlank(webServiceUrl)) {
            return ResultUtil.error("客户所属公司数据有误");
        }

        boolean isPushToERP = accountData.getBoolean("isPushToERP"); // 是否推送到ERP

        // 2 映射字段
        JSONObject filterData = filerAccount(accountData, khCompany);

        try {
            // 3 推送ERP
            log.info("推送erp客户接口parameter={}", filterData.toJSONString());
            DlcrU8WebService webService = new DlcrU8WebService(new URL(webServiceUrl));
            DlcrU8WebServiceSoap api = webService.getDlcrU8WebServiceSoap();
            ApiReturnInfo apiReturnInfo;
            if (isPushToERP) {

                // 如果是修改客户，先调用saveCustomerAuth接口
                // 检查客户 维度档案
                if (!khCompany.equals(DatasourceEnum.XIN_CAI_LIAO.getCompanyName())) {
                    String auth_accountId = "";
                    String erp_account_num = accountData.getString("ERP_account_num");
                    if (StringUtils.isBlank(erp_account_num)) {
                        auth_accountId = accountData.getString("account_num");
                    } else {
                        auth_accountId = erp_account_num;
                    }
                    ResultUtil<Object> authResult = pushAuth(accountData, webServiceUrl, khCompany, auth_accountId);
                    if (!authResult.getCode().equals(200)) {
                        return authResult;
                    }
                }

                apiReturnInfo = api.modifyCustomer(filterData.toJSONString());
                log.info("推送erp修改客户接口result={}", JSONObject.toJSONString(apiReturnInfo));
            } else {
                apiReturnInfo = api.addCustomer(filterData.toJSONString());
                log.info("推送erp新增客户接口result={}", JSONObject.toJSONString(apiReturnInfo));
            }

            if (apiReturnInfo.isIsSuccess()) {

                log.info(accountId + "成功推送erp客户数据");
                String billNum = apiReturnInfo.getBillNum();

                JSONObject updateData = new JSONObject();
                updateData.put("id", accountId);
                updateData.put("push_status", "成功");
                updateData.put("fail_reason", "");
                updateData.put("ERP_account_num", billNum);
                updateData.put("push_parameter", filterData.toJSONString());
                updateData.put("isPushToERP", true);
                List<JSONObject> list = new ArrayList<>();
                list.add(updateData);
                CrmApiUtil.batchUpdateDataByList(zohoRecord.getAccessToken(), list, crmPathConfig.getAccountModuleName());

                //推送客户银行
                pushBank(accountData, webServiceUrl);

                // 推送客户联系人
                pushContact(accountData, webServiceUrl, accountId, khCompany, 1, "");

                // 推送客户地址
                pushAddress(accountData, webServiceUrl, accountId, khCompany);

                // addCustomer,才调用saveCustomerAuth接口。modifyCustomer会提前调用
                if(!isPushToERP){
                    // 检查客户 维度档案
                    if (!khCompany.equals(DatasourceEnum.XIN_CAI_LIAO.getCompanyName())) {

                        String auth_accountId = "";
                        String erp_account_num = accountData.getString("ERP_account_num");
                        if (StringUtils.isBlank(erp_account_num)) {
                            auth_accountId = accountData.getString("account_num");
                        } else {
                            auth_accountId = erp_account_num;
                        }
                        ResultUtil<Object> authResult = pushAuth(accountData, webServiceUrl, khCompany, auth_accountId);
                        if (!authResult.getCode().equals(200)) {
                            return authResult;
                        }
                    }
                }


                return ResultUtil.success();
            } else {
                String errMsg = apiReturnInfo.getErrMsg();

                JSONObject updateData = new JSONObject();
                updateData.put("id", accountId);
                updateData.put("push_status", "失败");
                updateData.put("fail_reason", errMsg);
                updateData.put("push_parameter", filterData.toJSONString());
                List<JSONObject> list = new ArrayList<>();
                list.add(updateData);
                CrmApiUtil.batchUpdateDataByList(zohoRecord.getAccessToken(), list, crmPathConfig.getAccountModuleName());

                return ResultUtil.error(errMsg);
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        return ResultUtil.success();

    }

    @Override
    public ResultUtil<Object> getERPAccount(JSONObject json) {
        String cusCode = json.getString("cuscode");
        DlcrU8WebService webService;
        String customerByCusCode = "";
        try {
            webService = new DlcrU8WebService(new URL(DatasourceEnum.SU_ZHOU.getWebServiceUrl()));
            DlcrU8WebServiceSoap api = webService.getDlcrU8WebServiceSoap();
            customerByCusCode = api.getCustomerByCusCode(cusCode);
            System.out.println("getERPAccount=" + customerByCusCode);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return ResultUtil.success(customerByCusCode);
    }

    private JSONObject filerAccount(JSONObject accountData, String company) {
        JSONObject result = new JSONObject();

        String erp_account_num = accountData.getString("ERP_account_num");
        if (StringUtils.isBlank(erp_account_num)) {
            result.put("ccuscode", accountData.getString("account_num")); // 客户编码编号
            result.put("cCusHeadCode", accountData.getString("account_num")); // 客户总公司编码
        } else {
            result.put("ccuscode", erp_account_num); // 客户编码编号
            result.put("cCusHeadCode", erp_account_num); // 客户总公司编码
        }

        JSONObject secondaryIndustry = accountData.getJSONObject("SecondaryIndustry");// 二级行业
        if (Objects.nonNull(secondaryIndustry)) {
            String firstId = secondaryIndustry.getString("id");
            JSONObject dataById = CrmApiUtil.getDataById(zohoRecord.getAccessToken(), crmPathConfig.getSecondModuleName(), firstId);
            if (Objects.nonNull(dataById)) {
                result.put("cCCCode", dataById.getString("SecondaryIndustryCode")); // 所属分类 又叫 客户分类
            }
        }
        result.put("cCusName", accountData.getString("Account_Name")); // 客户名称
        result.put("cCusAbbName", accountData.getString("Account_Name")); // 客户简称

        result.put("cCusExch_name", "人民币"); // 币种
        result.put("cCusMngTypeCode", "999"); // 客户管理类型编码
        result.put("dCusDevDate", accountData.getString("FileCreatTime")); // 建档日期

        if (company.equals(DatasourceEnum.GONG_CHANG.getCompanyName())) {
            result.put("privilege_id", "98"); // 默认客户权限管理维度编码,001, 默认传  总部综合业务 98
        }
        //else {
        //    result.put("privilege_id", ""); // 默认客户权限管理维度编码
        //}

        JSONObject owner = accountData.getJSONObject("Owner");
        if (Objects.nonNull(owner)) {
            String ownerId = owner.getString("id");
            Map<String, String> data = CrmApiUtil.getUserCodeByCompany(zohoRecord.getAccessToken(), ownerId, company);
            result.put("cCusPPerson", data.get("personCode")); // 专营业务员编码
            if (company.equals(DatasourceEnum.GONG_CHANG.getCompanyName())) {
                result.put("cCusDepart", "12"); // 分管部门编码
            } else {
                result.put("cCusDepart", data.get("departCode")); // 分管部门编码
            }
        }
        //result.put("CustomerKCode", accountData.getString("account_category")); // 客户类别

        result.put("bRequestSign", accountData.getBoolean("sign_back")); // 需要签回
        result.put("cCusRegCode", accountData.getString("Duty_number")); // 税号
        result.put("cCusEmail", accountData.getString("Invoice_mailbox")); // 邮箱
        result.put("ccusaddress", accountData.getString("Billing_address")); // 开票地址
        //result.put("ccusphone", accountData.getString("Billing_telephone")); // 开票电话
        result.put("cCusHand", accountData.getString("Billing_telephone")); // 开票电话
        result.put("ccusperson", accountData.getString("Billing_contact")); // 开票联系人

        result.put("iCusCreLine", accountData.getString("credit_line")); // 信用额度
        result.put("cCusDefine4", accountData.getString("NYJDCode")); // 南亚客户
        result.put("iCusCreDate", accountData.getString("pay_day")); // 付款天数

        JSONObject firstIndustry = accountData.getJSONObject("FirstIndustry");// 一级行业
        if (Objects.nonNull(firstIndustry)) {
            String firstId = firstIndustry.getString("id");
            JSONObject dataById = CrmApiUtil.getDataById(zohoRecord.getAccessToken(), crmPathConfig.getFirstModuleName(), firstId);
            if (Objects.nonNull(dataById)) {
                result.put("cTrade", dataById.getString("SecondaryIndustryCode")); // 所属行业
            }
        }

        //result.put("code", accountData.getString("MultipleIndustryLabels")); // 多重行业标签
        //result.put("code", accountData.getString("KHCompany")); // 客户所属公司
        //result.put("super_dept", accountData.getString("KHDepartment")); // 客户所属部门
        //result.put("code", accountData.getString("transfer_date")); // 转交日期
        //result.put("code", accountData.getString("enterprise_type")); // 企业类型

        //result.put("code", accountData.getString("Billing_telephone")); // 开票电话
        //result.put("cbranch", accountData.getString("bank_deposit")); // 开户行
        //result.put("caccountnum", accountData.getString("Account_numberdata")); // 账号
        //result.put("code", accountData.getString("Line_number")); // 行号
        //result.put("code", accountData.getString("Invoice_mailbox")); // 发票邮箱
        //result.put("code", accountData.getString("General_taxpayer")); // 是否一般纳税人
        //result.put("code", accountData.getString("Website")); // 网站
        //result.put("ccussaprotocol", accountData.getString("pay_terms")); // 销售默认收付款协议编码
        //result.put("code", accountData.getString("GLJYkehu")); // 是否关联交易客户
        //result.put("code", accountData.getString("GLJYdate")); // 申请通过时间（关联交易）
        //result.put("code", accountData.getString("GLJYdirection")); // 关联交易方向
        //result.put("code", accountData.getString("MYkehu")); // 是否贸易客户
        //result.put("code", accountData.getString("JCkehu")); // 是否集采客户
        //result.put("code", accountData.getString("collection_customer_group")); // 所属集团
        //result.put("code", accountData.getString("YZbeian")); // 是否需要印章备案
        //result.put("code", accountData.getString("TSHTBASituation")); // 特殊合同备案情况
        //result.put("code", accountData.getString("TSHTBAStartDate")); // 特殊合同备案起始时间
        //result.put("code", accountData.getString("TSHTBAEndDate")); // 特殊合同备案终止时间

        getDifferentField(result, accountData, company);

        return result;
    }

    // 每个公司，字段取值不一样
    private void getDifferentField(JSONObject erpData, JSONObject crmData, String company) {

        String personCode = "";
        JSONObject zhuLi = crmData.getJSONObject("zhuli");
        if (Objects.nonNull(zhuLi)) {
            personCode = zhuLi.getString("name");
        }

        if (company.equals(DatasourceEnum.SU_ZHOU.getCompanyName())) { // 【苏州】
            erpData.put("cCusDefine9", personCode); // 助理
            erpData.put("cCusDefine8", crmData.getString("Billing_requirement")); // 发票要求
            erpData.put("ccdefine12", crmData.getString("pay_terms_start_time")); // 付款条件起始时间
            erpData.put("ccdefine13", crmData.getString("pay_terms_end_time")); // 付款条件终止时间
            erpData.put("cCusDefine13", crmData.getString("pay_day")); // 付款天数
            erpData.put("cCusDefine11", crmData.getString("MonthlyNode")); // 月结节点
            erpData.put("cCusDefine5", crmData.getString("NYJDkehu")); // 是否南亚建档客户
            erpData.put("cCusDefine4", crmData.getString("NYJDkehu")); // 南亚客户
            erpData.put("ccdefine11", crmData.getString("ShippingRequirementsDizhiku")); // 发货要求
            erpData.put("cCusDefine1", crmData.getString("pay_terms")); // 付款条件
        } else if (company.equals(DatasourceEnum.CHANG_ZHOU.getCompanyName())) { // 【常州】
            erpData.put("cCusDefine1", personCode); // 助理
            erpData.put("cCusDefine8", crmData.getString("Billing_requirement")); // 发票要求
            erpData.put("cCusDefine7", crmData.getString("ShippingRequirementsDizhiku")); // 发货要求
        } else if (company.equals(DatasourceEnum.DA_LIAN.getCompanyName())) { // 【大连总部】
            erpData.put("cCusDefine1", personCode); // 助理
            erpData.put("cCusDefine15", crmData.getString("pay_terms_start_time")); // 付款条件起始时间
            erpData.put("cCusDefine16", crmData.getString("pay_terms_end_time")); // 付款条件终止时间
            erpData.put("cCusDefine13", crmData.getString("pay_day")); // 欠款评估天数
            erpData.put("cCusDefine11", crmData.getString("MonthlyNode")); // 月结节点
            erpData.put("cCusDefine5", crmData.getString("NYJDkehu")); // 是否南亚建档客户
            erpData.put("cCusDefine4", crmData.getString("NYJDkehu")); // 南亚客户
            erpData.put("cCusDefine7", crmData.getString("ShippingRequirementsDizhiku")); // 发货要求
            erpData.put("cCusDefine8", crmData.getString("Billing_requirement")); // 发票要求
        } else if (company.equals(DatasourceEnum.XIN_CAI_LIAO.getCompanyName())) { // 【常州新材料】
            erpData.put("cCusDefine1", personCode); // 助理
            erpData.put("cCusDefine8", crmData.getString("Billing_requirement")); // 发票要求
            erpData.put("cCusDefine15", crmData.getString("pay_terms_start_time")); // 付款条件起始时间
            erpData.put("cCusDefine16", crmData.getString("pay_terms_end_time")); // 付款条件终止时间
            erpData.put("cCusDefine13", crmData.getString("pay_day")); // 欠款评估天数
            erpData.put("cCusDefine11", crmData.getString("MonthlyNode")); // 月结节点
            erpData.put("cCusDefine5", crmData.getString("NYJDkehu")); // 是否南亚建档客户
            erpData.put("cCusDefine4", crmData.getString("NYJDkehu")); // 南亚客户
            erpData.put("cCusDefine7", crmData.getString("ShippingRequirementsDizhiku")); // 发货要求
        } else if (company.equals(DatasourceEnum.GONG_CHANG.getCompanyName())) { // 【工厂】
            erpData.put("cCusDefine1", crmData.getString("ShippingRequirementsDizhiku")); // 发货要求
        }

    }

    /**
     * type = 1 ,客户模块里关联的联系人
     * type = 2 ,地址模块里关联的联系人
     */
    private void pushContact(JSONObject accountData, String webServiceUrl, String accountId, String company, int type, String contactId) throws MalformedURLException {

        List<JSONObject> contactList = new ArrayList<>();
        if (type == 1 && StringUtils.isBlank(contactId)) { // 客户关联的联系人
            String selectQuery = crmSqlQuery.getContactById(accountId);
            contactList = CrmApiUtil.COQLQuery(zohoRecord.getAccessToken(), selectQuery);
        } else if (type == 2 && StringUtils.isNotBlank(contactId)) {// 地址关联的联系人
            JSONObject dataById = CrmApiUtil.getDataById(zohoRecord.getAccessToken(), crmPathConfig.getContactModuleName(), contactId);
            contactList.add(dataById);
        }

        List<JSONObject> updateList = new ArrayList<>();
        List<JSONObject> erp_paramList = new ArrayList<>();

        for (JSONObject contact : contactList) {
            JSONObject json = new JSONObject();

            String auth_accountId = "";
            String erp_account_num = accountData.getString("ERP_account_num");
            if (StringUtils.isBlank(erp_account_num)) {
                auth_accountId = accountData.getString("account_num");
            } else {
                auth_accountId = erp_account_num;
            }
            json.put("cCusCode", auth_accountId); // 客户编码  /  所属客户
            String phone = contact.getString("Phone");
            if (StringUtils.isNotBlank(phone)) {
                json.put("cContactName", contact.getString("Last_Name") + phone); // 联系人名称 + 电话
            } else {
                json.put("cContactName", contact.getString("Last_Name")); // 联系人名称
            }

            // 在008总部的账套增加一个逻辑： 推送【南亚建档客户名称（总部专用）】到ERP的联系人自定义项1里
            if (company.equals(DatasourceEnum.DA_LIAN.getCompanyName())) {
                json.put("cHomePhone", contact.getString("AccountName_zongbu")); // 南亚建档客户名称（总部专用）
            }

            JSONObject owner = contact.getJSONObject("Owner");
            if (Objects.nonNull(owner)) {
                String ownerId = owner.getString("id");
                Map<String, String> data = CrmApiUtil.getUserCodeByCompany(zohoRecord.getAccessToken(), ownerId, company);
                json.put("cPrincipal", data.get("personCode")); // 负责人
            }
            json.put("cMobilePhone", contact.getString("Phone")); // 移动电话
            json.put("cConDepart", contact.getString("Department")); // 部门
            json.put("bcDutyID", contact.getString("Title")); // 职位/职称。职务是一个编码,取自职务档案

            json.put("bMajor",
                    !Objects.isNull(contact.getString("isMajor")) && contact.getString("isMajor").equals("是")); // 是否主要联系人
            json.put("cEmail", contact.getString("Email")); // 电子邮件
            json.put("cWorkAddress", contact.getString("work_place")); // 工作地址

            erp_paramList.add(json);
        }

        if (erp_paramList.size() > 0) {
            log.info("批量推送erp客户{}【联系人】接口parameter={}", accountId, JSONObject.toJSONString(erp_paramList));
            DlcrU8WebService webService = new DlcrU8WebService(new URL(webServiceUrl));
            DlcrU8WebServiceSoap api = webService.getDlcrU8WebServiceSoap();
            String s = api.saveCusContactList(JSONObject.toJSONString(erp_paramList));
            JSONArray erpList = JSONObject.parseArray(s);
            if (erpList.size() > 0) {
                List<JSONObject> list = erpList.toJavaList(JSONObject.class);
                log.info("批量推送erp客户{}【联系人】接口result={}", accountId, JSONObject.toJSONString(list));
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).getBoolean("IsSuccess")) {
                        String billID = list.get(i).getString("BillID");
                        JSONObject temp = new JSONObject();
                        temp.put("id", contactList.get(i).getString("id"));
                        temp.put("erp_code", billID);
                        updateList.add(temp);
                    } else {
                        log.error("推送erp客户{}【联系人】接口失败{}", accountId, list.get(i).toJSONString());
                    }
                }
            }
            //System.out.println("jsonObject1.toJSONString() = " + erpList.toJSONString());
            //ApiReturnInfo apiReturnInfo =
            //if (apiReturnInfo.isIsSuccess()) {
            //    String billNum = apiReturnInfo.getBillNum();
            //    JSONObject jsonObject = new JSONObject();
            //    jsonObject.put("id", contact.getString("id"));
            //    jsonObject.put("erp_code", billNum);
            //    updateList.add(jsonObject);
            //} else {
            //    log.error("推送erp客户【联系人】接口失败，" + apiReturnInfo.getErrMsg());
            //}

        }

        if (updateList.size() > 0) {
            CrmApiUtil.batchUpdateDataByList(zohoRecord.getAccessToken(), updateList, crmPathConfig.getContactModuleName());
            log.info("成功推送erp客户{}【联系人】", accountId);
        }

    }

    private void pushAddress(JSONObject accountData, String webServiceUrl, String accountId, String khCompany) throws MalformedURLException {

        // 客户关联的地址库
        String selectQuery = crmSqlQuery.getAddressByAccount(accountId);
        List<JSONObject> addressList = CrmApiUtil.COQLQuery(zohoRecord.getAccessToken(), selectQuery);
        //String searchUrl = "(AccountName.id:equals:" + accountId + ")&sort_order=asc&sort_by=id";
        //List<JSONObject> addressList = CrmApiUtil.getModuleDataBySearch(zohoRecord.getAccessToken(), crmPathConfig.getAddressSearchUrl() + searchUrl);
        List<JSONObject> erpData = new ArrayList<>();
        for (JSONObject address : addressList) {
            JSONObject json = new JSONObject();


            String auth_accountId = "";
            String erp_account_num = accountData.getString("ERP_account_num");
            if (StringUtils.isBlank(erp_account_num)) {
                auth_accountId = accountData.getString("account_num");
            } else {
                auth_accountId = erp_account_num;
            }

            json.put("cCusCode", auth_accountId); // 客户编码
            json.put("cAddCode", address.getString("Name")); // 收货地址编码

            JSONObject shippingContactDizhiku = address.getJSONObject("ShippingContactDizhiku"); // 收货联系人
            if (Objects.nonNull(shippingContactDizhiku)) {
                String id = shippingContactDizhiku.getString("id");
                JSONObject dataById = CrmApiUtil.getDataById(zohoRecord.getAccessToken(), crmPathConfig.getContactModuleName(), id);
                if (Objects.nonNull(dataById)) {

                    // 先将地址里的联系人推送到ERP
                    //pushContact(accountData, webServiceUrl, accountId, khCompany, 2, dataById.getString("id"));
                    dataById = CrmApiUtil.getDataById(zohoRecord.getAccessToken(), crmPathConfig.getContactModuleName(), id);
                    String erpCode = dataById.getString("erp_code");
                    if (StringUtils.isNotBlank(erpCode)) {
                        json.put("cLinkPerson", dataById.get("erp_code")); // 联系人
                    }
                }
            }

            String sheng = address.getString("Sheng"); // 省
            String Shi = address.getString("Shi"); // 市
            String AddressDizhiku = address.getString("AddressDizhiku"); // 详细地址
            json.put("cDeliverAdd", sheng + Shi + AddressDizhiku); // 收货地址
            JSONObject endAccount = address.getJSONObject("EndAccount");
            if (Objects.nonNull(endAccount)) {

                String endAccountId = endAccount.getString("id");
                JSONObject dataById = CrmApiUtil.getDataById(zohoRecord.getAccessToken(), crmPathConfig.getAccountModuleName(), endAccountId);
                if (Objects.nonNull(dataById)) {
                    //json.put("cDeliverUnit", dataById.getString("EndAccount")); // 收货单位
                    json.put("cDeliverUnit", dataById.getString("Account_Name")); // 收货单位
                }
            }

            json.put("bDefault", address.getString("default").equals("是") ? 1 : 0); // 默认值
            erpData.add(json);
        }

        log.info("推送erp客户{}【地址】接口parameter={}", accountId, JSONObject.toJSONString(erpData));
        DlcrU8WebService webService = new DlcrU8WebService(new URL(webServiceUrl));
        DlcrU8WebServiceSoap api = webService.getDlcrU8WebServiceSoap();
        String result = api.saveCusDeliverAddList(JSONObject.toJSONString(erpData));
        JSONArray array = JSONArray.parseArray(result);
        boolean isSuccess = true;
        if (array.size() > 0) {
            List<JSONObject> list = array.toJavaList(JSONObject.class);
            for (JSONObject jsonObject : list) {
                if (!jsonObject.getBoolean("IsSuccess")) {
                    log.error("推送erp客户【地址】接口失败，" + jsonObject.toJSONString());
                    isSuccess = false;
                }
            }
        }
        if (isSuccess) {
            log.info("成功推送erp客户{}【地址】", accountId);
        } else {
            log.info("失败，推送erp客户{}【地址】", accountId);
        }
    }

    private void pushBank(JSONObject accountData, String webServiceUrl) throws MalformedURLException {

        String accountId = accountData.getString("id");
        JSONObject json = new JSONObject();
        //json.put("cBank", accountData.getString("aaaaaa")); // 所属银行
        json.put("cBranch", accountData.getString("bank_deposit")); // 开户银行
        json.put("cAccountName", accountData.getString("bank_name")); // 帐号名称

        String auth_accountId = "";
        String erp_account_num = accountData.getString("ERP_account_num");
        if (StringUtils.isBlank(erp_account_num)) {
            auth_accountId = accountData.getString("account_num");
        } else {
            auth_accountId = erp_account_num;
        }
        json.put("cCusCode", auth_accountId); // 客户编码
        json.put("cAccountNum", accountData.getString("Account_numberdata")); // 银行账号
        json.put("bDefault", true); // 必填 true 或者false，代表该条记录是否是客户的默认银行帐号
        //json.put("cCusPrinvince", accountData.getString("aaaaaa")); // 省/自治区
        //json.put("cCusCity", accountData.getString("aaaaaa")); // 市/县
        //json.put("cCusCBBDepId", accountData.getString("aaaaaa")); // 机构号
        //json.put("cCusBranchId", accountData.getString("aaaaaa")); // 联行号
        //json.put("cCusBranchIdSec", accountData.getString("aaaaaa")); // 联行号Ⅱ（中银专用

        log.info("推送erp客户{}【银行】接口parameter={}", accountId, json.toJSONString());
        DlcrU8WebService webService = new DlcrU8WebService(new URL(webServiceUrl));
        DlcrU8WebServiceSoap api = webService.getDlcrU8WebServiceSoap();
        ApiReturnInfo apiReturnInfo = api.saveCustomerBank(json.toJSONString());
        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(apiReturnInfo));
        boolean isSuccess = true;
        if (!jsonObject.getBoolean("isSuccess")) {
            log.error("推送erp客户{}【银行】接口失败{}", accountId, jsonObject.toJSONString());
            isSuccess = false;
        }
        if (isSuccess) {
            log.info("成功推送erp客户【银行】");
        } else {
            log.info("失败，推送erp客户【银行】");
        }
    }

    private ResultUtil<Object> pushAuth(JSONObject accountData, String webServiceUrl, String company, String account_num) throws MalformedURLException {

        String accountId = accountData.getString("id");

        JSONObject owner = accountData.getJSONObject("Owner");
        List<JSONObject> authList = new ArrayList<>();

        int index = 1;
        JSONObject deleteJson = new JSONObject();
        deleteJson.put("action", "delete");
        deleteJson.put("id", index++);
        deleteJson.put("privilege_id", "all");
        deleteJson.put("account_id", account_num);
        authList.add(deleteJson);


        String codeByCompanyName = U8SystemApiUtil.getCodeByCompanyName(company);

        if (Objects.nonNull(owner)) {
            String ownerName = owner.getString("name");

            // 助理信息管理
            String searchUrl = "((accountCode:equals:" + codeByCompanyName + ")and(Name:equals:" + ownerName + "))";
            List<JSONObject> contactList = CrmApiUtil.getModuleDataBySearch(zohoRecord.getAccessToken(), crmPathConfig.getZhuLiSearchUrl() + searchUrl);

            if (contactList.size() > 0) {
                JSONObject leader = contactList.get(0);

                // 去CRM客户维度档案中，查询该用户的管理维度是多少
                String ownSearchUrl = "((account_name:equals:" + codeByCompanyName + ")and(Name:equals:" + ownerName + "))";
                List<JSONObject> ownerList = CrmApiUtil.getModuleDataBySearch(zohoRecord.getAccessToken(), crmPathConfig.getCustomerAuthSearchUrl() + ownSearchUrl);

                if (ownerList.size() == 0) {
                    return ResultUtil.error("该用户的管理维度暂未查到，请联系管理员！");
                }
                List<JSONObject> temp_ownerList = new ArrayList<>();
                for (JSONObject jsonObject : ownerList) {
                    if (jsonObject.getString("Name").equals(ownerName)) {
                        temp_ownerList.add(jsonObject);
                    }
                }

                if (temp_ownerList.size() > 0) {
                    JSONObject jsonObject = temp_ownerList.get(0);
                    String cADCode = jsonObject.getString("cADCode");// 维度编码
                    if (StringUtils.isBlank(cADCode)) {
                        return ResultUtil.error("该用户的管理维度暂未查到，请联系管理员！");
                    }
                    JSONObject ownerTemp = new JSONObject();
                    ownerTemp.put("action", "insert");
                    ownerTemp.put("id", index++);
                    ownerTemp.put("privilege_id", cADCode);
                    ownerTemp.put("account_id", account_num);
                    authList.add(ownerTemp);
                }

                if (company.equals(DatasourceEnum.SU_ZHOU.getCompanyName())) {

                    JSONObject leaderObj = leader.getJSONObject("User_leader"); // 上级领导
                    if (Objects.nonNull(leaderObj)) {
                        String leaderName = leaderObj.getString("name");
                        // 去CRM客户维度档案中，查询该用户的管理维度是多少
                        String leaderSearchUrl = "((account_name:equals:" + codeByCompanyName + ")and(Name:equals:" + leaderName + "))";
                        List<JSONObject> leaderList = CrmApiUtil.getModuleDataBySearch(zohoRecord.getAccessToken(), crmPathConfig.getCustomerAuthSearchUrl() + leaderSearchUrl);

                        List<JSONObject> temp_leaderList = new ArrayList<>();
                        for (JSONObject jsonObject : leaderList) {
                            if (jsonObject.getString("Name").equals(ownerName)) {
                                temp_leaderList.add(jsonObject);
                            }
                        }
                        if (temp_leaderList.size() > 0) {
                            JSONObject jsonObject = temp_leaderList.get(0);
                            String cADCode = jsonObject.getString("cADCode");// 维度编码
                            JSONObject ownerTemp = new JSONObject();
                            ownerTemp.put("action", "insert");
                            ownerTemp.put("id", index);
                            ownerTemp.put("privilege_id", cADCode);
                            ownerTemp.put("account_id", account_num);
                            authList.add(ownerTemp);
                        }
                    }
                }
                // 推送ERP 客户管理维度
                log.info("推送erp客户{}管理维度接口parameter={}", accountId, JSONObject.toJSONString(authList));
                DlcrU8WebService webService = new DlcrU8WebService(new URL(webServiceUrl));
                DlcrU8WebServiceSoap api = webService.getDlcrU8WebServiceSoap();
                String result = api.saveCustomerAuth(JSONObject.toJSONString(authList));
                JSONArray json = JSONArray.parseArray(result);
                boolean isSuccess = true;
                if (json.size() > 0) {
                    List<JSONObject> list = json.toJavaList(JSONObject.class);
                    for (JSONObject jsonObject : list) {
                        if (!jsonObject.getBoolean("success")) {
                            log.error("推送erp客户{}【管理维度】接口失败{}", accountId, jsonObject.toJSONString());
                            isSuccess = false;
                        }
                    }
                }

                if (isSuccess) {
                    log.info("成功推送erp客户{}【管理维度】", accountId);
                } else {
                    log.info("失败，推送erp客户{}【管理维度】", accountId);
                }

            } else {
                log.error("客户所有者在维度档案模块的账套数据为空，请填写！");
            }

        }
        return ResultUtil.success();
    }

    @Override
    public ResultUtil<Object> pushAccountContactToERP(JSONObject json) {
        log.info("pushAccountContactToERP,parameter={}", json.toJSONString());

        String contactId = json.getString("contactId");
        if (StringUtils.isBlank(contactId)) {
            return ResultUtil.error("contactId为空");
        }
        JSONObject contactData = CrmApiUtil.getDataById(zohoRecord.getAccessToken(), crmPathConfig.getContactModuleName(), contactId);
        if (Objects.isNull(contactData)) {
            return ResultUtil.error(contactId + "数据为空");
        }
        JSONObject accountName = contactData.getJSONObject("Account_Name");
        if (Objects.isNull(accountName)) {
            return ResultUtil.error("客户字段为空");
        }
        String accountId = accountName.getString("id");
        JSONObject accountData = CrmApiUtil.getDataById(zohoRecord.getAccessToken(), crmPathConfig.getAccountModuleName(), accountId);
        String khCompany = accountData.getString("KHCompany");
        String webServiceUrl = U8SystemApiUtil.getWebUrlByCompanyName(khCompany);
        // 推送客户联系人
        try {
            pushContact(accountData, webServiceUrl, accountId, khCompany, 1, "");
        } catch (Exception e) {
            System.out.println("e.getMessage() = " + e.getMessage());
        }
        return ResultUtil.success();
    }

    @Override
    public ResultUtil<Object> pushAddressToERP(JSONObject json) {
        log.info("pushAddressToERP,parameter={}", json.toJSONString());

        String addressId = json.getString("addressId");
        if (StringUtils.isBlank(addressId)) {
            return ResultUtil.error("addressId空");
        }
        JSONObject addressData = CrmApiUtil.getDataById(zohoRecord.getAccessToken(), crmPathConfig.getAddressModuleName(), addressId);
        if (Objects.isNull(addressData)) {
            return ResultUtil.error(addressId + "数据为空");
        }
        JSONObject accountName = addressData.getJSONObject("AccountName");
        if (Objects.isNull(accountName)) {
            return ResultUtil.error("客户字段为空");
        }
        String accountId = accountName.getString("id");
        JSONObject accountData = CrmApiUtil.getDataById(zohoRecord.getAccessToken(), crmPathConfig.getAccountModuleName(), accountId);
        String khCompany = accountData.getString("KHCompany");
        String webServiceUrl = U8SystemApiUtil.getWebUrlByCompanyName(khCompany);
        // 推送客户地址
        try {
            pushAddress(accountData, webServiceUrl, accountId, khCompany);
        } catch (Exception e) {
            System.out.println("e.getMessage() = " + e.getMessage());
        }
        return ResultUtil.success();
    }


}
